﻿#region Using

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Vk.Authorization;
using Vk.Exceptions;

#endregion

namespace Vk
{
    /// <summary>
    ///     Класс для коммуникации с сервером VkAPI
    /// </summary>
    public sealed class RequestManager
    {
        private readonly VkSession _session;

        /// <summary>
        ///     Whether the last request was performed successfully
        /// </summary>
        public bool MethodSuccessed { get; private set; }

        /// <summary>
        /// Operations' timeout
        /// </summary>
        public int Timeout { get; set; }

        public RequestManager(VkSession session)
        {
            _session = session;
        }

        /// <summary>
        ///     Выполняет запрос
        /// </summary>
        public async Task<ApiNode> Execute(ApiQuery query)
        {
            var request = query.ToString(_session);
            var apiResponseString = await Send(request);

            if (string.IsNullOrWhiteSpace(apiResponseString))
            {
                throw new ApiRequestEmptyAnswerException(
                    "Сервер возвратил пустой ответ или истекло время ожидания ответа");
            }

            var response = new ApiJsonNode(apiResponseString).SelectNode("/response");
            var errorNode = response.SelectNode("/error");
            if (errorNode == null)
            {
                MethodSuccessed = true;
            }
            else
            {
                var error = new ApiError(errorNode);

                if (error.Code != 14)
                    throw new ApiRequestErrorException(error);

                //Captcha needed
                var captchaInfo = new ApiCaptchaInfo(errorNode);
                throw new CaptchaNeededException(error, captchaInfo);
            }

            return response;
        }

        /// <summary>
        ///     Отправляет запрос на сервер
        /// </summary>
        /// <param name="url"> Адрес сервера для запроса </param>
        public async Task<string> Send(string url)
        {
            try
            {
                var request = (HttpWebRequest) WebRequest.Create(new Uri(url));
                request.Timeout = Timeout;
                request.UserAgent = "VkAPI.NET " + Api.Version;
                using (var response = (HttpWebResponse) await request.GetResponseAsync())
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    return await sr.ReadToEndAsync();
                }
            }
            catch (Exception e)
            {
                throw new ApiRequestNullResult("Error: " + e.Message);
            }
        }
    }
}